<?php
include_once 'simple_html_dom.php';
include_once  'xml.class.php';
ini_set('memory_limit', '512M');
set_time_limit(0);
function echoMem()
{
    $MaxMem = round(memory_get_peak_usage() / 1024) ;
    $MEM =round(memory_get_usage() /1024) ;
    echo "記憶體目前用掉".$MEM." , 最多用掉".$MaxMem.PHP_EOL;
}

//for ...每年

//if 存在月  .xml ==> skip~
//年..for美日 ... if M != prev -->把已經push的..處理
//依樣

//Load each html
//2012年9月15日
//二零一二年 七月(小)三十
//壬辰年 己酉月 己卯日

function getFileName($y,$m)
{
    return 'month/'.$y.'-'.$m.".xml";
}
function isProcessed($y,$m)
{
    $fn= getFileName($y,$m);
    if(file_exists($fn))
        return true;
    return false;
}

function getHtmlName($day)
{
    return '../fetch/'.date('Y',$day).'/'.date('Y-n-j',$day).'.html';
}
function processDay($day)
{

    $fn=getHtmlName($day);
    if(file_exists($fn)==false)
        return null;
    echo "---".date('Y-n-j',$day). PHP_EOL;

    $page= file_get_contents($fn);
    $html = str_get_html($page);


    try {
        $result=array();
        $result['date']=date('Y/n/j',$day);

        //$a=$html->find('a[class=currentPage]',0);
        $t1=$html->find('table[class="bx fright cboth"]',0);
        $t3=$html->find('/html/body/div[4]/div/div/div[2]/table/tbody',0);

        // /html/body/div[4]/div/div/div[2]/table/tbody/tr/td[2]
        // /html/body/div[4]/div/div/div[2]/table/tbody/tr/td
        //  /html/body/div[4]/div/div/div[2]/table/tbody/tr/td[3]
        $s1=$t1->children[0]->children[1]->innertext;
        $pos=strpos($s1,'年柱');
        if($pos!=false)
        {
            $result['GJ_year']=$t1->children[0]->children[1]->nodes[2]->innertext;
            $result['GJ_month']=$t1->children[0]->children[2]->nodes[2]->innertext;
            $result['GJ_day']=$t1->children[0]->children[3]->nodes[2]->innertext;
        }else
        {
            $result['GJ_year']=$t1->children[0]->children[2]->nodes[2]->innertext;
            $result['GJ_month']=$t1->children[0]->children[3]->nodes[2]->innertext;
            $result['GJ_day']=$t1->children[0]->children[4]->nodes[2]->innertext;
        }

        $result['w']=date('w',$day);

        $t2=$html->find('table[class="bx"]',1);
        // $t2->children[0]->children[2]->plaintext = 公元 1902年1月1日 星期三
        //lunar  $t2->children[1]->children[1]->plaintext  = 一九零一年 十一月(小) 廿二

        //找農曆 /html/body/div[4]/div/div/div[2]/table[2]/tbody/tr[2]/th

        $cs=count($t2->children);
        for($i=0;$i<$cs;$i++)
        {
            $s1=$t2->children[$i]->children[0]->plaintext;
            if(strpos($s1,'【宜】')!==false)
            {
                if(count($t2->children[$i]->children)==3)
                    $result['yes']=$t2->children[$i]->children[2]->plaintext;
                else
                    $result['yes']=$t2->children[$i]->children[1]->plaintext;

                echo $result['yes'].PHP_EOL;
            }
            if(strpos($s1,'【忌】')!==false)
            {
                if(count($t2->children[$i]->children)==3)
                    $result['no']=$t2->children[$i]->children[2]->plaintext;
                else
                    $result['no']=$t2->children[$i]->children[1]->plaintext;

                echo $result['no'].PHP_EOL;
            }
            if(strpos($s1,'农历')!==false)
            {
                if(count($t2->children[$i]->children)==3)
                    $lunar=trim($t2->children[$i]->children[2]->plaintext);
                else
                    $lunar=trim($t2->children[$i]->children[1]->plaintext);

                $pos1=strpos($lunar,'(');
                $pos2=strpos($lunar,')');
                if(($pos1>0&&$pos2>0))
                {
                    $lunar=substr($lunar,0, $pos1).substr($lunar,$pos2+1);
                }
                $result['lunar']=$lunar;

            }
        }


        echo $result['GJ_year'].' '.$result['GJ_month'].' '.$result['GJ_day'].' '.$result['lunar']. PHP_EOL;
    } catch (Exception $e) {
        echo "Error:".date('Y-n-j',$day). PHP_EOL;
        echo $e->getMessage(). PHP_EOL;
    }
    unset($html);
    unset($page);


    //宜  $t2->children[10]->children[2]->plaintext
    //忌  $t2->children[11]->children[2]->plaintext

    return $result;
}
function processDays($days)
{
    $length = count($days);
    if($length<27)
        return;
    //pick day one
    $d=$days[0];
    $y=date('Y',$d);
    $m=date('n',$d);
    if(isProcessed($y, $m))
        return;
    $dayarray=array();
    try {
        for($i=0;$i<$length;$i++)
        {
            $daycontent=processDay($days[$i]);
            if($daycontent!=null)
            {
                $dayarray[]=$daycontent;
            }
            echoMem();
        }
    } catch (Exception $e) {
        echo $e->getCode(). PHP_EOL;
        echo $e->getMessage(). PHP_EOL;
        echo $e->getTrace(). PHP_EOL;
        return null;
    }
    return $dayarray;
    echo "process:".$y.'-'.$m.' count:'.$length. PHP_EOL;
}
function processYear($dateF,$count)
{
    $year=date('Y',$dateF);
    $date=$dateF;
    $curM=1;
    $days=array();

    for($i=0;$i<$count;$i++)
    {
        $y=date('Y',$date);
        $m=date('n',$date);
        if(isProcessed($y,$m))
            continue;
        if($m!=$curM)
        {
            $rr=processDays($days);
            unset($rr);
            $days=array();
            $days[]=$date;
            $curM=$m;
        }else
        {
            $days[]=$date;
        }
        $date=strtotime(date('Y-n-j',$date)."+1 day");
    }


}

function processMonth($y,$m)
{
    if(isProcessed($y,$m))
    {
        echo "Processed Skip:".$y.'-'.$m.PHP_EOL;
        return;
    }
    
    $date=strtotime($y.'-'.$m.'-1');    
    $days=array();
    for($i=0;$i<31;$i++)
    {
        if(date('n',$date)!=$m)
            break;
        $rr=processDay($date);
        if($rr!=null)
            $days[]=$rr;
        $date=strtotime(date('Y-n-j',$date)."+1 day");        
        echoMem();
    }
    if(count($days)<27)
        return;
    $ser=my_xml_serialize($days,$y,$m);
    $fn=getFileName($y,$m);
    file_put_contents($fn,$ser);
    unset($ser);
    
};

function my_xml_serialize($data,$y,$m)
{
    $s="";
    foreach($data as $entry)
    {
        $s.='<day date="'.$entry['date'].'">'.xml_serialize_X($entry,0,2).'</day>';
    }
    return '<?xml version="1.0" encoding="UTF-8"?><data  year="'.$y.'" month="'.$m.'"  >'.$s.'</data>';

}

//processMonth('1902','1');



if (empty($_GET['y'])) {
  for($y=1902;$y<=2020;$y++)
  {
      for($m=1;$m<=12;$m++)
      {
       $url='http://127.0.0.1/LuckyNote/YellowCal/convert/ToMonth.php?y='.$y.'&m='.$m;
       echo $url.'</br>';
        try {
          $fp= file_get_contents($url);
          unset($fp);            
        } catch (Exception $e) {
        }
                  
      }      
  }   
    
}else
{
    echo $_GET['y'];
    echo $_GET['m'];
    processMonth($_GET['y'],$_GET['m']);
}








/*
 $date=strtotime('1902-01-01');
$dateF=$date;

for($i=0;$i<120;$i++)
{
processYear($dateF,367);
$dateF=strtotime(date('Y-n-j',$dateF)."+1 year");
}
*/

//$date=strtotime('1902-02-28');
//processDay($date);






